<template>
  <div class="contentWrapper">
    <div class="contentTitle">
      <div class="title">职途报告</div>
      <el-tabs v-model="currentTab" @tab-click="handleClickTab">
        <el-tab-pane label="自动生成" name="aiCreate"></el-tab-pane>
        <el-tab-pane label="顾问解析报告" name="upload"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="contentContainer" v-show="currentTab === 'upload'">
      <div class="contentTop">
        <el-button type="primary" round plain size="mini" @click="updateFile">
          <i class="el-icon-upload el-icon--right"></i>
          上传</el-button
        >
        <el-button
          v-if="currentUploadWordFile"
          type="primary"
          round
          plain
          size="mini"
          v-has="'download'"
          @click="handleDownloadClick('word')"
        >
          <i class="el-icon-download"></i>下载(WORD)</el-button
        >
        <el-button
          v-if="currentUploadPdfFile"
          type="primary"
          round
          plain
          size="mini"
          v-has="'download'"
          @click="handleDownloadClick('pdf')"
        >
          <i class="el-icon-download"></i>下载(PDF)</el-button
        >
        <el-upload
          @click.stop
          v-show="false"
          class="upload-file"
          :multiple="false"
          id="uploadFile"
          :action="uploadAction"
          :accept="accept"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
        >
        </el-upload>
      </div>
      <div class="contentMain" v-loading="uploadLoading && currentUploadFile">
        <div
          :class="[
            judgeFileType(currentUploadFile) === 'empty' || !currentUploadFile
              ? ''
              : 'officeWrapper'
          ]"
        >
          <el-scrollbar class="scroll">
            <vue-office-pdf
              :src="currentUploadFile"
              @rendered="renderedHandler"
              @error="errorHandler"
              v-if="judgeFileType(currentUploadFile) === 'pdf'"
            />
            <vue-office-docx
              :src="currentUploadFile"
              @rendered="renderedHandler"
              @error="errorHandler"
              v-if="judgeFileType(currentUploadFile) === 'word'"
            />
            <div
              class="empty-wrap"
              v-if="
                judgeFileType(currentUploadFile) === 'empty' ||
                !currentUploadFile
              "
            >
              <Empty />
              <el-button
                type="primary"
                class="mr23 spe-btn"
                round
                primary
                size="big"
                v-has="'upload'"
                @click="uploadMedia"
              >
                <elan-svg icon="noFileUpload"></elan-svg>
                <span>上传文件</span></el-button
              >
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
    <div class="contentContainer" v-show="currentTab === 'aiCreate'">
      <div class="contentTop">
        <el-button
          type="primary"
          round
          plain
          size="mini"
          :disabled="createLoading"
          @click="createReportFn"
        >
          <i :class="createLoading ? 'el-icon-loading' : 'el-icon-setting'"></i>
          生成报告</el-button
        >
        <el-button
          v-if="currentAIWordFile"
          type="primary"
          round
          plain
          size="mini"
          v-has="'download'"
          @click="handleDownloadClick('word')"
        >
          <i class="el-icon-download"></i>下载(WORD)</el-button
        >
        <el-button
          v-if="currentAIPdfFile"
          type="primary"
          round
          plain
          size="mini"
          v-has="'download'"
          @click="handleDownloadClick('pdf')"
        >
          <i class="el-icon-download"></i>下载(PDF)</el-button
        >
      </div>
      <div class="contentMain" v-loading="createLoading && currentAIPdfFile">
        <div
          :class="[
            judgeFileType(currentAIPdfFile) === 'empty' || !currentAIPdfFile
              ? ''
              : 'officeWrapper'
          ]"
        >
          <el-scrollbar class="scroll">
            <vue-office-pdf
              :src="currentAIPdfFile"
              @rendered="renderedHandler"
              @error="errorHandler"
              v-if="judgeFileType(currentAIPdfFile) === 'pdf'"
            />
            <vue-office-docx
              :src="currentAIPdfFile"
              @rendered="renderedHandler"
              @error="errorHandler"
              v-if="judgeFileType(currentAIPdfFile) === 'word'"
            />
            <div
              class="empty-wrap"
              v-if="
                judgeFileType(currentAIPdfFile) === 'empty' || !currentAIPdfFile
              "
            >
              <Empty />
              <el-button
                class="mr23 spe-btn"
                type="primary"
                round
                primary
                size="big"
                :disabled="createLoading"
                @click="createReportFn"
              >
                <i
                  :class="createLoading ? 'el-icon-loading' : 'el-icon-setting'"
                ></i>
                生成报告</el-button
              >
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import VueOfficePdf from '@vue-office/pdf';
import VueOfficeDocx from '@vue-office/docx';
import { download } from '@/utils/fileSaver';
import {
  getCareerPathReport,
  uploadCareerPathReport,
  getReport,
  createReport
} from '@/api/index';
export default {
  name: 'careerPathReport',
  components: {
    VueOfficePdf,
    VueOfficeDocx
  },
  props: {
    selectedRow: {
      type: Object,
      default: () => ({})
    }
  },
  mounted() {
    this.getCareerPathReportFn();
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  data() {
    return {
      MAX_RETRY_TIMES: 5,
      retryCount: 0,
      currentTab: 'aiCreate',
      currentAIPdfFile: '',
      currentAIWordFile: '',
      currentUploadFile: '',
      currentUploadPdfFile: '',
      currentUploadWordFile: '',
      aiFileList: [],
      uploadFileList: [],
      timer: null,
      fileGetting: false,
      createLoading: false,
      reportGenerated: false,
      pageNumPending: null,
      uploadLoading: true,
      uploadAction: 'https://upload.yl1001.com/upload/files/save',
      accept: '.pdf,.PDF,.docx'
    };
  },
  methods: {
    async createReportFn() {
      const temp = this.selectedRow.userRightList.find(
        (item) => item.finishType == 2
      );
      if (!temp) {
        this.$message.warning(
          '当前用户还没完成任意一项权益，无法生成职途报告！'
        );
        return;
      }
      this.createLoading = true;
      const params = {
        cardType: this.selectedRow.cardType,
        personId: this.selectedRow.personId
      };
      const res = await createReport(params);
      if (res.code == 200) {
        setTimeout(() => {
          this.startRequest();
        }, 10000);
      }
    },
    startRequest() {
      this.timer = setInterval(() => {
        if (!this.reportGenerated && this.retryCount < this.MAX_RETRY_TIMES) {
          this.getAIReportFn();
        }
      }, 10000);
    },
    endRequest() {
      clearInterval(this.timer);
      this.createLoading = false;
      this.timer = null;
    },
    async getAIReportFn() {
      try {
        const res = await getReport({
          personId: this.selectedRow.personId
        });
        if (res.code === 200 && res.data.stateV2 !== undefined) {
          const stateV2 = res.data.stateV2;
          if (stateV2 === 1) {
            this.currentAIPdfFile = res.data.pdfUrlV2 || '';
            this.currentAIWordFile = res.data.wordUrlV2 || '';
            this.reportGenerated = true; // 报告已生成，停止循环请求
            this.endRequest();
          } else if (stateV2 === 0) {
            this.$message.info('职途报告正在生成中');
          } else if (stateV2 === 2) {
            this.endRequest();
            this.$message.error('职途报告生成失败');
            this.reportGenerated = true; // 虽然报告未成功生成，但也要停止循环请求
          }
        } else if (res.code === 201) {
          this.endRequest();
          this.$message.warning('请点击生成报告按钮生成职途报告');
        } else {
          this.endRequest();
          this.$message.error(res.status_desc);
        }
      } catch (err) {
        this.endRequest();
        this.$message.error(err.message);
      }

      // 每次尝试后增加重试计数
      this.retryCount++;

      // 如果超过最大重试次数且报告仍未生成
      if (!this.reportGenerated && this.retryCount >= this.MAX_RETRY_TIMES) {
        this.$message.error('超过最大重试次数，职途报告仍在生成中，请稍后再试');
        this.createLoading = false;
      }
    },
    handleClickTab(tab) {
      this.currentTab = tab.name;
    },
    renderedHandler() {
      this.uploadLoading = false;
      console.log('渲染完成');
    },
    errorHandler() {
      this.$message.error('pdf正在渲染中，请稍后...');
      this.uploadLoading = false;
      console.log('渲染失败');
    },
    handleDownloadClick(type) {
      if (this.currentTab == 'upload') {
        // download(
        //   this.currentUploadFile,
        //   `${this.selectedRow.personName}的职途报告(顾问上传)`
        // );
        switch (type) {
          case 'pdf':
            download(
              this.currentUploadPdfFile,
              `${this.selectedRow.personName}的职途报告(自动生成)`
            );
            break;
          case 'word':
            download(
              this.currentUploadWordFile,
              `${this.selectedRow.personName}的职途报告(自动生成)`
            );
            break;
          default:
            break;
        }
      } else {
        // download(
        //   this.currentAIWordFile,
        //   `${this.selectedRow.personName}的职途报告(自动生成)`
        // );
        switch (type) {
          case 'pdf':
            download(
              this.currentAIPdfFile,
              `${this.selectedRow.personName}的职途报告(自动生成)`
            );
            break;
          case 'word':
            download(
              this.currentAIWordFile,
              `${this.selectedRow.personName}的职途报告(自动生成)`
            );
            break;
          default:
            break;
        }
      }
    },
    // 判断是pdf文件还是word文件
    judgeFileType(str) {
      if (!str) return 'empty';
      let res = str.substring(str.length - 1, str.length);
      if (res === 'x' || res === 'X' || res === 'c' || res === 'C') {
        return 'word';
      } else if (res === 'f' || res === 'F') {
        return 'pdf';
      } else {
        return 'empty';
      }
    },
    uploadMedia() {
      if (!this.selectedRow.consultantId) {
        this.$message.error('该用户还没绑定顾问！');
        return;
      }
      // 防抖
      if (this.fileGetting) {
        return;
      }
      this.fileGetting = true;
      setTimeout(() => {
        this.fileGetting = false;
      }, 1000);
      setTimeout(() => {
        document.querySelector('#uploadFile').querySelector('input').click();
      }, 100);
    },
    async updateFile() {
      this.uploadMedia();
    },
    // 获取自主上传的职途报告
    async getCareerPathReportFn() {
      const res = await getCareerPathReport({
        personId: this.selectedRow.personId
      });
      this.currentUploadFile =
        res.data?.info?.pdfUrl || res.data?.info?.wordUrl;
      this.currentUploadPdfFile = res.data?.info?.pdfUrl || '';
      this.currentUploadWordFile = res.data?.info?.wordUrl || '';
      this.currentAIPdfFile =
        res.data?.info?.pdfUrlV2 || res.data?.info?.wordUrlV2;
      this.currentAIWordFile = res.data?.info?.wordUrlV2 || '';
    },
    handleUploadSuccess(data) {
      this.currentUploadFile = data.data[0];
      uploadCareerPathReport({
        personId: this.selectedRow.personId,
        consultantId: this.selectedRow.consultantId,
        extra: data.data[0]
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '上传成功'
            });
            this.getCareerPathReportFn();
          } else {
            this.$message.error(res.status_desc);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    beforeUpload(files) {
      if (
        [
          'application/pdf',
          'application/vnd.openxmlformats-officedocument.presentationml.presentation',
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/vnd.ms-powerpoint'
        ].indexOf(files.type) == -1
      ) {
        this.$message.error('请上传正确的文本格式文件，如pdf doc docx');
        return false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.contentWrapper {
  height: 100%;
  .contentTitle {
    margin-bottom: 17px;
    display: flex;
    align-items: center;
    .title {
      font-size: 22px;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: 800;
      color: #222222;
      line-height: 30px;
    }
    ::v-deep .el-tabs {
      flex: 1;
    }
    ::v-deep .el-tabs__item {
      font-size: 16px;
    }
    ::v-deep .el-tabs__header .el-tabs__nav-wrap {
      padding: 0;
      margin-left: 30px;
    }
  }
  .contentContainer {
    height: calc(100% - 62px);
    margin-right: 24px;
    .contentTop {
      display: flex;
      align-items: center;
      margin-bottom: 14px;
      position: relative;
      .contentSmallTitle {
        font-size: 18px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #222222;
        line-height: 25px;
        margin-right: 26px;
        font-weight: bold;
        &::before {
          content: '';
          display: inline-block;
          width: 5px;
          height: 15px;
          background: #7052ff;
          border-radius: 100px;
          margin-right: 8px;
        }
      }

      .downloadBtn {
        margin-left: 14px;
        ::v-deep.el-button.is-round {
          background-color: transparent;
        }
        .svg-icon {
          font-size: 16px;
        }
      }
      img {
        width: 16px;
        height: 16px;
        margin-right: 5px;
      }
    }
    .contentMain {
      width: 100%;
      height: calc(100% - 62px);
      display: flex;
      justify-content: center;
      .officeWrapper {
        border-radius: 8px 0px 8px 8px;
        border: 1px solid #e6e5e7;
        overflow: hidden;
      }
      .empty {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }
      /deep/.vue-office-pdf-wrapper {
        background-color: #ffffff !important;
        width: 100%;
        overflow: hidden;
      }
      /deep/ .docx-wrapper {
        background-color: #ffffff !important;
        width: 100%;
        overflow: hidden;
      }
      /deep/.vue-office-pdf {
        overflow-x: hidden;
      }
      /deep/ .vue-office-docx {
        overflow-x: hidden;
      }

      .scroll {
        height: 100%;
        .uploadNewFileBtn {
          display: flex;
          flex-direction: row;
          justify-content: center;
          margin-top: 23px;
          .svg-icon {
            font-size: 16px;
          }
          /deep/.el-button.is-round span {
            color: #ffffff;
          }
          /deep/.el-button--primary.is-plain {
            color: #7052ff;
            background: #7052ff;
            border-color: #7052ff;
            width: 130px;
            height: 40px;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            font-size: 14px;
          }
          span {
            margin-left: 5px;
            color: #ffffff;
          }
        }
      }
    }
    .qrContainer {
      display: flex;
      justify-content: center;
      align-items: center;
      .qrCodeContainer {
        width: 100%;
        height: 505px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
    }
  }
  .fileOverview {
    position: relative;
    .overViewTitle {
      width: 109px;
      height: 22px;
      font-size: 16px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #222222;
      line-height: 22px;
      position: absolute;
      margin-top: -30px;
    }
  }
  .fileLi,
  .activeLi {
    padding-left: 15px;
    cursor: pointer;
    font-size: 16px;
    font-family: PingFang-SC, PingFang-SC;
    line-height: 30px;
    height: 30px;
    width: 163px;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    margin-bottom: 12px;
  }
  .fileLi {
    color: #888888;
  }
  .activeLi {
    background: #f2e9ff;
    color: #7052ff;
  }
}
.mr23 {
  margin-top: 23px;
}
.empty-wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: auto;
}
.spe-btn {
  ::v-deep .el-button--mini.is-round {
    padding: 12px 16px !important;
  }
}
::v-deep .el-button.is-round {
  span {
    display: flex;
    align-items: center;
  }
}
::v-deep .el-tabs__item {
  color: #999 !important;
}
::v-deep .el-tabs__item.is-active {
  color: #7052ff !important;
}
::v-deep .el-icon--right,
.el-icon-download,
.el-icon-setting {
  margin: 0 8px 0 0;
  font-size: 14px;
}
</style>
